<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" onsubmit="return false;">
      <el-form-item label="仓库名称" prop="condition[gitName|like]">
        <el-input
          v-model="queryParams['condition[gitName|like]']"
          placeholder="请输入仓库名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图标" width="80" align="center" prop="loginName">
        <template slot-scope="scope">
          <!-- <i v-if="scope.row.gitType == 'gitlab' || scope.row.gitType == 'github' || scope.row.gitType == 'bitbucket'" :class="'git-icon fab fa-' + scope.row.gitType" />
          <i v-else class="git-icon fab fa-git-alt fa-fw" /> -->
          <div class="sc-icons">
              <img :src="giticon(scope.row)" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="仓库名称" align="left" width="150" prop="gitName" />
      <el-table-column label="简介" align="left" prop="fieldProp" :show-overflow-tooltip="true" />
      <el-table-column label="状态" width="80" prop="hasStatus">
        <template slot-scope="scope">
        <el-switch
            v-model="scope.row.hasStatus"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
         </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.hasBing != 1"
            size="mini"
            type="warning"
            class="bing-btn"
            @click="bingGit(scope.row)"
          > <i class="fas fa-link fa-fw"></i> 绑定账号</el-button>
          <el-button
            v-else
            size="mini"
            class="bing-btn"
            type="danger"
            @click="unBingGit(scope.row)"
          > <i class="fas fa-unlink fa-fw"></i> 解除绑定</el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="fas fa-feather"
            @click="handleUpdate(scope.row)"
          > 修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          > 删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库类型对话框 -->
    <el-dialog :title="title" :rules="rules" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

          <el-form-item label="仓库类型" prop="gitType">
            <el-radio-group v-model="form.gitType">
              <el-radio :label="item.value" v-for="(item , index) in svnList" :key="index" :selected="item.status == 1">
                   {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="仓库名称" prop="gitName">
            <el-input v-model="form.gitName" placeholder="例如:企业代码管理平台" />
          </el-form-item>
          <el-form-item label="仓库简介" prop="fieldProp">
            <el-input v-model="form.fieldProp" placeholder="例如:test-cicd,没有则自动创建" />
          </el-form-item>
          
        </el-form>

        <el-link href="https://gitlab.your-domain.com" style="margin-left:50px" type="primary" target="_blank">PersonToken获取方式</el-link>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定github/gitee -->
    <el-dialog
      title="提示"
      :visible.sync="githubDialogVisible"
      width="30%">
      <el-timeline>
        <el-timeline-item
          @click="openGithubBing(activity)"
          v-for="(activity, index) in activities"
          :key="index">
          <a v-if="activity.type === 'openLink'" :href="githubBingLink" target="_blank"> {{activity.content}} </a>
          <a v-if="activity.type === 'closeBack'" href="javascript:void(0)" @click="closeGithub"> {{activity.content}} </a>
        </el-timeline-item>
      </el-timeline>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeGithub">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 绑定gitlab -->
    <el-dialog
      title="提示"
      :visible.sync="gitlabDialogVisible"
      width="700px">

      <el-form ref="formGitlab" :model="formGitlab" :rules="rules" label-width="80px">

          <el-form-item label="仓库地址" prop="gitHost">
            <el-input v-model="formGitlab.gitHost" placeholder="例如:https://gitlab.your-domain.com" />
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="formGitlab.userName" placeholder="例如:企业代码管理平台" />
          </el-form-item>
          <el-form-item label="密钥" prop="accessPrivateToken">
            <el-input v-model="formGitlab.accessPrivateToken" placeholder="请输入仓库管理密钥" />
          </el-form-item>

        </el-form>

        <el-link href="https://help.aliyun.com/document_detail/202197.htm?spm=5176.8351553.help.dexternal.7f231991B2jC51#section-h93-qn7-zz2" style="margin-left:50px" type="primary" target="_blank">PersonToken获取方式</el-link>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormGitlab">提 交</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { listBuildGit, getBuildGit, delBuildGit, addBuildGit, updateBuildGit, exportBuildGit } from "./api";
import { unBing , getGithubAuthurl , bingFormGitlab } from "@/api/Git" ;

export default {
  name: "Type",
  components: {
  },
  data() {
    return {
      svnList:[
        {icon:'fab fa-gitlab' , value:'gitlab', name:'Gitlab' , isConnect:true , status:1 },
      ],
      activities: [{
          content: '点击前往源代码仓库登录',
          type:'openLink' 
        }, {
          content: '返回控制台确认绑定完成',
          type:'closeBack' 
      }],
      // 绑定github链接
      githubBingLink: '' , 
      // 是否显示github会话
      githubDialogVisible: false ,
      // 显示gitlab会话
      gitlabDialogVisible: false ,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库类型表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        'condition[gitName|like]': null,
        dictType: null,
        status: null,
      },
      // 表单参数
      form: {
        gitType: 'gitlab' ,
      },
      formGitlab: {
        gitlabId: '' ,
      },
      // 表单校验
      rules: {
          gitType: [
            { required: true, message: '选择仓库类型', trigger: 'blur' },
          ],
          userName: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ],
          gitName: [
            { required: true, message: '请输入仓库名称', trigger: 'blur' },
          ],
          gitHost: [
            { required: true, message: '请输入仓库地址', trigger: 'blur' },
          ],
          gitNamespace: [
            { required: true, message: '请选择仓库空间', trigger: 'blur' },
          ],
          gitType: [
            { required: true, message: '请选择仓库地址', trigger: 'blur' },
          ],
          accessPrivateToken: [
            { required: true, message: '请输入仓库密钥', trigger: 'blur' },
          ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询仓库类型列表 */
    getList() {
      this.loading = true;
      listBuildGit(this.queryParams).then(response => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dictName: null,
        dictType: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    // 获取git 图标
    giticon(item){
      const gitType = item.gitType ; 
      if(gitType === 'gitea'){
        return require("@/asserts/images/giticon/gitea.png") ;
      } else if(gitType === 'gitee'){
        return require("@/asserts/images/giticon/gitee.png") ;
      } else if(gitType === 'gitlab'){
        return require("@/asserts/images/giticon/gitlab.png") ;
      }
    } ,
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加仓库类型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBuildGit(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改仓库类型";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBuildGit(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBuildGit(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 保存submitFormGitlab
    submitFormGitlab() {
      this.$refs["formGitlab"].validate(valid => {
        if (valid) {
          bingFormGitlab(this.formGitlab).then(response => {
            console.log('response = ' + response) ;
            this.msgSuccess("绑定成功");
            this.gitlabDialogVisible = false;
            this.getList();
          });
        }
      });
    },
    // 绑定 bingGit
    bingGit(row){

      const gitType = row.gitType ; 
      if(gitType === 'alicode' || gitType === 'bitbucket'){
        this.$message({
          message: '仓库'+gitType+'绑定暂未开通.',
          type: 'warning'
        });
        return ; 
      }

      console.log('git type = ' + gitType) ;
      if(gitType === 'github' || gitType === 'gitee' || gitType === 'gitea'){
        // 配置githu链接
        this.githubDialogVisible = true ;
        getGithubAuthurl(row.gitType).then(res => {
          if(res.code == 200){
            this.githubBingLink = res.data ;
          }else{
            this.msgSuccess("删除成功");
          }
        }) ;
      } else if(gitType === 'gitlab'){
        this.formGitlab.gitlabId = row.id ; 
        this.gitlabDialogVisible = true ;
      }

    } ,
    // 解除gith绑定
    unBingGit(row){
      const gitType = row.gitType ; 

      this.$confirm('是否确认要解绑"' + gitType + '"仓库么?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
        }).then(() => {
          unBing(row.id , gitType).then(res => {
            console.log('res = ' + res) ;
            if(res.code == 200){
              this.msgSuccess("解绑" + gitType+ "成功");
              this.getList() ;
            }
          }) ;
        })
    } , 
    // 关闭github链接
    closeGithub(){
      this.githubDialogVisible = false ;
      this.gitlabDialogVisible = false ; 
      this.getList() ;
    } ,
    // 绑定github 
    openGithubBing(activity){
      console.log('activity = ' + activity) ;
    } ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除仓库类型编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBuildGit(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有仓库类型数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportBuild仓库(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
    }
  }
};
</script>

<style lang="scss" scoped>
.git-icon {
  font-size: 30px;
}

.bing-btn {
  padding-left:10px !important; 
  padding-right: 10px !important;
}

.sc-icons{
  height: 100%;
  font-size: 30px;
  margin-right: 10px;
  color: #005bd4;

  img{
    width: 35px;
    background: #f6f8fc;
    border-radius: 50%;
  }
}

</style>